package jumpingnotes.dao.hibernate;

import java.util.List;

import jumpingnotes.dao.GroupTopicDao;
import jumpingnotes.model.entity.GroupTopic;
import net.jf.lucene.analysis.mmseg.MMSegAnalyzer;

import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.queryParser.ParseException;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.search.FullTextSession;
import org.hibernate.search.Search;
import org.springframework.orm.hibernate3.HibernateCallback;

public class GroupTopicHibernateDao extends GenericHibernateDao<GroupTopic> implements GroupTopicDao
{
	public GroupTopicHibernateDao()
	{
		super(GroupTopic.class);
	}

	@SuppressWarnings("unchecked")
	public List<GroupTopic> findGroupTopicByGroupId(final int groupId, final int status, final int firstResult, final int maxResults)
	{
		return (List<GroupTopic>) getHibernateTemplate().execute(new HibernateCallback()
		{
			public Object doInHibernate(Session session) throws HibernateException
			{
				Query query = session.createQuery("select distinct gt from GroupTopic gt where gt.group.groupId=:groupId and gt.status=:status order by gt.updateTime desc");
				query.setInteger("groupId", groupId);
				query.setInteger("status", status);
				
				if (firstResult >= 0)
					query.setFirstResult(firstResult);
				if (maxResults > 0)
					query.setMaxResults(maxResults);
				
				return query.list();
			}
		});
	}

	@SuppressWarnings("unchecked")
	public void indexGroupTopic()
	{
		Session session = getSession();
		FullTextSession fullTextSession = Search.createFullTextSession(session);

		List<GroupTopic> groupTopicList = session.createCriteria(GroupTopic.class).list();
		for (GroupTopic groupTopic : groupTopicList)
		{
			fullTextSession.index(groupTopic);
		}
	}

	@SuppressWarnings("unchecked")
	public List<GroupTopic> searchGroupTopic(String keyword, int firstResult, int maxResults)
	{
		Session session = getSession();
		FullTextSession fullTextSession = Search.createFullTextSession(session);

		try
		{
			MultiFieldQueryParser parser = new MultiFieldQueryParser(new String[] { "title", "body" },
					new MMSegAnalyzer());
			org.apache.lucene.search.Query query = parser.parse(keyword);
			Query hibQuery = fullTextSession.createFullTextQuery(query, GroupTopic.class);

			if (firstResult >= 0)
				hibQuery.setFirstResult(firstResult);
			if (maxResults > 0)
				hibQuery.setMaxResults(maxResults);

			List<GroupTopic> result = hibQuery.list();
			return result;
		}
		catch (ParseException e)
		{
			e.printStackTrace();
			return null;
		}
	}
}
